package xdu.lz.pc;

/**
 * 多线程下出现问题
 */
public class Code00_SimplePC {

    public static void main(String[] args) throws Exception {
        Code00_SimplePC pc = new Code00_SimplePC();
        for (int i = 0; i < 2; i++) {
            new Thread(()->{
                try {
                    pc.produce();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },"P"+i).start();
            new Thread(()->{
                try {
                    pc.consume();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },"C"+i).start();
        }

    }

    private final Object LOCK = new Object();

    private boolean isProduced = false;

    private int counter = 0;

    public void produce() throws InterruptedException {

        while (true) {
            synchronized (LOCK) {
                if (isProduced) {
                    LOCK.wait();
                } else {
                    System.out.println(Thread.currentThread().getName() + "生产了:" + (++counter));
                    isProduced = true;
                    LOCK.notify();
                    Thread.sleep(10);
                }
            }
        }
    }

    public void consume() throws InterruptedException {
        while (true) {
            synchronized (LOCK) {
                if (!isProduced) {
                    LOCK.wait();
                } else {
                    System.out.println(Thread.currentThread().getName() + "消费了:" + (counter));
                    isProduced = false;
                    LOCK.notify();
                    Thread.sleep(10);
                }
            }
        }
    }
}
